package com.nowoe.data.parse;

import com.alibaba.druid.pool.DruidDataSource;
import com.nowoe.data.config.Configuration;
import com.nowoe.data.io.Resources;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.util.List;
import java.util.Properties;

/**
 * @author 倚栏听风 2023/9/14 15:40
 */
public class XMLConfigBuilder {
    private final Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * xml解析
     *
     * @return Configuration
     */
    public Configuration parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        //获取根节点
        Element rootElement = document.getRootElement();
        List<Node> nodes = rootElement.selectNodes("//property");
        //解析数据库配置信息
        Properties properties = new Properties();
        for (Node node : nodes) {
            Element el = (Element) node;
            String name = el.attributeValue("name");
            String value = el.attributeValue("value");
            properties.setProperty(name, value);
        }
        //创建数据源
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getProperty("driverClassName"));
        druidDataSource.setUrl(properties.getProperty("url"));
        druidDataSource.setUsername(properties.getProperty("username"));
        druidDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(druidDataSource);

        //解析映射配置文件
        List<Node> mappers = rootElement.selectNodes("//mapper");
        Element el = (Element) mappers.get(0);
        String mapperPath = el.attributeValue("resource").split(":")[1];
        URL url = this.getClass().getClassLoader().getResource(mapperPath);
        File dir = new File(url.getFile());
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
        for (File file : dir.listFiles()) {
            try {
                xmlMapperBuilder.parse(new FileInputStream(file));
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
        return configuration;
    }
}
